package product;

import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ProductUpdate extends JInternalFrame {
	Map<String, ProductData> hm = new HashMap<String, ProductData>();
	boolean mdf;
	int row;

	ProductData pd;
	String[] rows = {"Code", "Name", "Cost", "Ea", "Tot", "Date"};
	DefaultTableModel dtm = new DefaultTableModel(null, rows);
	Vector<String> RowData;
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");


	private JTextField pcInput;
	private JButton btnSearch;
	private JScrollPane scrollPane;
	private JTable table;
	private JLabel lblNewLabel;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_3;
	private JTextField pcInput2;
	private JTextField pnInput;
	private JTextField cosInput;
	private JTextField eaInput;
	private JTextField totInput;
	private JButton btnMod;
	private JButton btnDel;
	private JButton btnSearchAll;
	private JButton btnClr;

	public ProductUpdate() {
		super("ProductUpdate",true,true,false,false);		

		setBounds(100, 100, 463, 415);
		getContentPane().setLayout(null);
		getContentPane().add(getPcInput());
		getContentPane().add(getBtnSearch());
		getContentPane().add(getScrollPane());
		getContentPane().add(getLblNewLabel());
		getContentPane().add(getLabel());
		getContentPane().add(getLabel_1());
		getContentPane().add(getLabel_2());
		getContentPane().add(getLabel_3());
		getContentPane().add(getPcInput2());
		getContentPane().add(getPnInput());
		getContentPane().add(getCosInput());
		getContentPane().add(getEaInput());
		getContentPane().add(getTotInput());
		getContentPane().add(getBtnMod());
		getContentPane().add(getBtnDel());
		getContentPane().add(getBtnSearchAll());
		getContentPane().add(getBtnClr());


		setTblAlignment(table); // 금액 부분 오른쪽 정렬 메소드
		setCoulmnSize(table); 	// JTable 각 Column 의 칸을 지정, 마우스 드래그 앤 드롭으로 열섞임 방지.
		table.setRowSorter(new TableRowSorter(dtm)); // 각 column 별로 sort 할 수 있다. 하지만 값이 꼬임.
		//table.convertRowIndexToModel(row);

	}

	public void setTblAlignment(JTable t){
		// DefaultTableCellHeaderRenderer 생성 (가운데 정렬을 위한)
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();

		// DefaultTableCellHeaderRenderer의 정렬을 가운데 정렬로 지정
		dtcr.setHorizontalAlignment(SwingConstants.RIGHT);

		// 정렬할 테이블의 ColumnModel을 가져옴
		TableColumnModel tcm = table.getColumnModel();

		// 반복문을 이용하여 원하는 테이블의 정렬을 지정할 수도 있다.
		tcm.getColumn(4).setCellRenderer(dtcr);
	}

	public void setCoulmnSize(JTable t){

		t.getTableHeader().setReorderingAllowed(false);      
		//테이블 컬럼의 이동을 방지한다. 이거 안쓰면 마우스로 드로그 앤 드롭으로 엉망진창이 될수 있다.

		t.getColumnModel().getColumn(0).setPreferredWidth(30);
		t.getColumnModel().getColumn(0).setResizable(false);
		t.getColumnModel().getColumn(1).setPreferredWidth(30);
		t.getColumnModel().getColumn(2).setPreferredWidth(30);
		t.getColumnModel().getColumn(3).setPreferredWidth(30);
		t.getColumnModel().getColumn(4).setPreferredWidth(30);
		//t.getColumnModel().getColumn(5).setPreferredWidth(80);
		
	}


	public void setD(Map<String, ProductData> map, boolean a){
		this.hm = map;
		this.mdf=a;
	}

	private JTextField getPcInput() {
		if (pcInput == null) {
			pcInput = new JTextField();
			pcInput.setBounds(12, 10, 116, 21);
			pcInput.setColumns(10);
		}
		return pcInput;
	}
	private JButton getBtnSearch() {
		if (btnSearch == null) {
			btnSearch = new JButton("조회");
			btnSearch.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(pcInput.getText().equals("")){ // 조회 란이 공백일때,
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다."); 
						return;
					}						
					try{
						for (int i=dtm.getRowCount()-1; i>-1; i--) { // Table 비우기.
							dtm.removeRow(i);
						}
						String s = pcInput.getText();				
						Set<String> st = hm.keySet();	
						Iterator<String> it = st.iterator();
						int temp = dtm.getRowCount();
						while(it.hasNext()){
							pd = hm.get(it.next());
							if(pd.getpCode().contains(s) 
									|| pd.getpName().contains(s) 
									|| pd.getCost() == Integer.parseInt(s)){	// 제품 코드, 제품 명, 제품 단가 중 하나만 만족하면 검색.	// 날짜검색 추가.(현재 미구현)						

								RowData = new Vector<String>();
								RowData.add(pd.getpCode());
								RowData.add(pd.getpName());
								RowData.add(String.valueOf(pd.getCost()));
								RowData.add(String.valueOf(pd.getEa()));
								RowData.add(pd.decimalFormat()+" 원");
								RowData.add(sd.format(pd.getNal()));
								dtm.addRow(RowData);

							}
						}
						mdf=true; // 수정여부

						if(temp == dtm.getRowCount()){
							JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
							return;
						}
						btnMod.setEnabled(true);
						btnDel.setEnabled(true);
					}catch(NullPointerException ex){
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
					}

				}
			});
			btnSearch.setBounds(140, 9, 91, 23);
		}
		return btnSearch;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 41, 423, 220);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable(dtm);
			
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					int a = table.getSelectedRow();
					row=a;
					table.convertRowIndexToModel(a);
					pcInput2.setText(String.valueOf(dtm.getValueAt(a, 0))); // 해당 텍스트 필드에 데이터 세팅.
					pnInput.setText(String.valueOf(dtm.getValueAt(a, 1)));
					cosInput.setText(String.valueOf(dtm.getValueAt(a, 2)));
					eaInput.setText(String.valueOf(dtm.getValueAt(a, 3)));
					totInput.setText((String)dtm.getValueAt(a, 4));
					
				}
			});
		}
		return table;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("제품코드");
			lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel.setBounds(12, 274, 57, 15);
		}
		return lblNewLabel;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제품명");
			label.setHorizontalAlignment(SwingConstants.RIGHT);
			label.setBounds(12, 299, 57, 15);
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("단가");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(250, 274, 57, 15);
		}
		return label_1;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("수량");
			label_2.setHorizontalAlignment(SwingConstants.RIGHT);
			label_2.setBounds(250, 299, 57, 15);
		}
		return label_2;
	}
	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("금액");
			label_3.setHorizontalAlignment(SwingConstants.RIGHT);
			label_3.setBounds(250, 324, 57, 15);
		}
		return label_3;
	}
	private JTextField getPcInput2() {
		if (pcInput2 == null) {
			pcInput2 = new JTextField();
			pcInput2.setEditable(false);
			pcInput2.setBounds(81, 271, 116, 21);
			pcInput2.setColumns(10);
		}
		return pcInput2;
	}
	private JTextField getPnInput() {
		if (pnInput == null) {
			pnInput = new JTextField();
			pnInput.setEditable(false);
			pnInput.setColumns(10);
			pnInput.setBounds(81, 296, 116, 21);
		}
		return pnInput;
	}
	private JTextField getCosInput() {
		if (cosInput == null) {
			cosInput = new JTextField();
			cosInput.setColumns(10);
			cosInput.setBounds(319, 271, 116, 21);
		}
		return cosInput;
	}
	private JTextField getEaInput() {
		if (eaInput == null) {
			eaInput = new JTextField();
			eaInput.setColumns(10);
			eaInput.setBounds(319, 296, 116, 21);
		}
		return eaInput;
	}
	private JTextField getTotInput() {
		if (totInput == null) {
			totInput = new JTextField();
			totInput.setHorizontalAlignment(SwingConstants.RIGHT);
			totInput.setEditable(false);
			totInput.setColumns(10);
			totInput.setBounds(319, 321, 116, 21);
		}
		return totInput;
	}
	private JButton getBtnMod() {
		if (btnMod == null) {
			btnMod = new JButton("수정");
			btnMod.setEnabled(false);
			btnMod.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						if(cosInput.getText().trim().equals("")){ // 공백 또는 스페이스 공백 입력시 메세지 출력
							JOptionPane.showMessageDialog(null, "빈칸을 채워주세요");
							return;
						}else{
							Date temp = hm.get(pcInput2.getText()).nal; // 생산날짜 초기화 방지용 temp
							ProductData pd = new ProductData(pcInput2.getText(), pnInput.getText(), 
									Integer.parseInt(eaInput.getText()), Integer.parseInt(cosInput.getText()),temp); // 수정된 데이터 저장.
							hm.put(pcInput2.getText(), pd);
							JOptionPane.showMessageDialog(null, "데이터가 수정되었습니다");
							totInput.setText(String.valueOf(pd.decimalFormat()) + " 원"); //수정 후 금액 다시 표시.

							pcInput.requestFocus();
							btnSearch.setEnabled(true);
							btnMod.setEnabled(false);
							btnDel.setEnabled(false);
							mdf=true; // 수정여부
						}
					}catch(NumberFormatException nfe){
						JOptionPane.showMessageDialog(null, "단가와 수량은 숫자만 입력해주세요.");
					}									
				}
			});
			btnMod.setBounds(250, 349, 91, 23);
		}
		return btnMod;
	}
	private JButton getBtnDel() {
		if (btnDel == null) {
			btnDel = new JButton("삭제");
			btnDel.setEnabled(false);
			btnDel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					int yn = JOptionPane.showConfirmDialog(null, "정말로 삭제하시겠습니까?");
					if(yn == JOptionPane.YES_OPTION){
						hm.remove(pcInput2.getText());
						JOptionPane.showMessageDialog(null, "데이터가 삭제되었습니다");
						pcInput.setText("");
						pnInput.setText("");
						cosInput.setText("");
						eaInput.setText("");
						totInput.setText("");
						pcInput2.setText("");

						dtm.removeRow(row);

						pcInput.requestFocus();

						btnMod.setEnabled(false);
						btnDel.setEnabled(false);
						btnSearch.setEnabled(true);
						mdf=true; // 수정여부
					}else{
						JOptionPane.showMessageDialog(null, "삭제가 취소되었습니다");
					}				
				}
			});
			btnDel.setBounds(344, 349, 91, 23);
		}
		return btnDel;
	}
	private JButton getBtnSearchAll() {
		if (btnSearchAll == null) {
			btnSearchAll = new JButton("전체조회");
			btnSearchAll.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{						
						Set<String> st = hm.keySet();	
						Iterator<String> it = st.iterator();
						if(st.isEmpty()){  // Set 에 키가 하나도 들어있지 않을때.
							JOptionPane.showMessageDialog(null, "데이터가 존재하지 않습니다.");
							return;
						}
						for (int i=dtm.getRowCount()-1; i>-1; i--) { // Table 비우기.
							dtm.removeRow(i);
						}						
						while(it.hasNext()){
							pd = hm.get(it.next());													

							RowData = new Vector<String>();
							RowData.add(pd.getpCode());
							RowData.add(pd.getpName());
							RowData.add(String.valueOf(pd.getCost()));
							RowData.add(String.valueOf(pd.getEa()));
							RowData.add(String.valueOf(pd.decimalFormat()) + " 원");
							RowData.add(sd.format(pd.getNal()));
							dtm.addRow(RowData);

						}						
						btnMod.setEnabled(true);
						btnDel.setEnabled(true);						
					}catch(NullPointerException ex){
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
					}

				}
			});
			btnSearchAll.setBounds(243, 9, 91, 23);
		}
		return btnSearchAll;
	}
	private JButton getBtnClr() {
		if (btnClr == null) {
			btnClr = new JButton("Clear");
			btnClr.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					pcInput.setText("");
					pnInput.setText("");
					cosInput.setText("");
					eaInput.setText("");					
					pcInput2.setText("");
					totInput.setText("");
					for (int i=dtm.getRowCount()-1; i>-1; i--) {
						dtm.removeRow(i);
					}
					pcInput.requestFocus();

				}
			});
			btnClr.setBounds(344, 9, 91, 23);
		}
		return btnClr;
	}
}
